package com.zhanglong.kotlinfish.Util.Web

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Message
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.text.TextUtils
import android.view.View
import android.webkit.*
import com.lb.materialdesigndialog.impl.MaterialDialogNormal
import com.zhanglong.kotlinfish.BuildConfig
import com.zhanglong.kotlinfish.FishActivity
import org.jetbrains.anko.alert
import java.io.File
import java.util.*


class WebViewSettingUtil constructor (val context: AppCompatActivity, val webView:WebView, val callBack:WebSettingCallBack) {

    private val REQUEST_CODE_ALBUM = 0x01
    private val REQUEST_CODE_CAMERA = 0x02
    private val REQUEST_CODE_PERMISSION_CAMERA = 0x03
    private var uploadMessageAboveL: ValueCallback<Array<Uri>>? = null
    private var mCurrentPhotoPath: String? = null
    private var mLastPhothPath: String? = null
    private var mThread: Thread? = null

    interface WebSettingCallBack {
        fun onSuccess()
        fun onFaild()
    }

    fun loadUrl(url:String) {
        webView.loadUrl(url)
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_CODE_ALBUM || requestCode == REQUEST_CODE_CAMERA) {
            //取消拍照或者图片选择时
            if (resultCode != Activity.RESULT_OK) {
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL!!.onReceiveValue(null)
                    uploadMessageAboveL = null
                }
            }
            //拍照成功和选取照片时
            if (resultCode == Activity.RESULT_OK) {
                var imageUri: Uri? = null
                when (requestCode) {
                    REQUEST_CODE_ALBUM ->
                        if (data != null) {
                            imageUri = data.data
                        }
                    REQUEST_CODE_CAMERA ->
                        if (!mCurrentPhotoPath.isNullOrBlank()) {
                            val file = File(mCurrentPhotoPath)
                            val localUri = Uri.fromFile(file)
                            val localIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri)
                            context.sendBroadcast(localIntent)
                            imageUri = Uri.fromFile(file)
                            mLastPhothPath = mCurrentPhotoPath
                        }
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL!!.onReceiveValue(arrayOf<Uri>(imageUri!!))
                    uploadMessageAboveL = null

                }

            }

        }
    }
    @SuppressLint("SetJavaScriptEnabled", "WrongViewCast")

    fun userDefaultSetting(bgResourceId:Int){

        webView.setBackgroundColor(ContextCompat.getColor(context, android.R.color.transparent))
        webView.setBackgroundResource(bgResourceId)
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null)

        val webSettings = webView.settings
        webSettings.allowFileAccess = true
        webSettings.useWideViewPort = true
        webSettings.loadWithOverviewMode = true
        webSettings.domStorageEnabled = true
        webSettings.databaseEnabled = true
        webSettings.builtInZoomControls = true
        webSettings.displayZoomControls = false
        webSettings.cacheMode = WebSettings.LOAD_NO_CACHE
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        webSettings.loadsImagesAutomatically = true
        webSettings.defaultTextEncodingName = "utf-8"
        webSettings.allowFileAccess = true
        webSettings.allowFileAccessFromFileURLs = true
        webSettings.javaScriptEnabled = true
        webSettings.setSupportZoom(true)
        webSettings.mixedContentMode = 0

        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                if (newProgress == 100) {
                    callBack.onSuccess()
                }
            }
            override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
                context.alert(message,"提示") {
                    positiveButton(""){
                        result.confirm()
                    }
                }
                return true
            }

            override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: WebChromeClient.FileChooserParams): Boolean {
                uploadMessageAboveL = filePathCallback
                showDialogPickPicture()
                return true
            }
        }

        webView.webViewClient = object :WebViewClient() {
            // 6.0以下执行
            override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
                super.onReceivedError(view, errorCode, description, failingUrl)
                callBack.onFaild()
            }
            // 6.0以上执行
            override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
                super.onReceivedError(view, request, error)
                callBack.onFaild()
            }
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }

    }


    fun showDialogPickPicture() {
        val dialog = MaterialDialogNormal(context)
        dialog.setTitle("提示")
        dialog.setCancelable(true)
        dialog.setMessage("请选择图片上传方式")
        dialog.setPositiveButton("相机") { dialog, which ->
            dialog.dismiss()
            //请求拍照权限
            if (!mLastPhothPath.isNullOrBlank()){
                //上一张拍照的图片删除
                mThread = Thread(Runnable {
                    val file = File(mLastPhothPath)
                    file?.delete()
                    mHandler!!.sendEmptyMessage(1)
                })
                mThread!!.start()
            }
            else{
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                    takePhoto()
                }
                else {
                    ActivityCompat.requestPermissions(context as FishActivity, arrayOf(Manifest.permission.CAMERA), REQUEST_CODE_PERMISSION_CAMERA)
                }
            }
        }
        dialog.setNegativeButton("相册") { dialog, which ->
            dialog.dismiss()
            chooseAlbumPic()
        }

        dialog.setOnDialogDismissListener {
            if (uploadMessageAboveL != null) {
                uploadMessageAboveL!!.onReceiveValue(null)
                uploadMessageAboveL = null
            }
        }
        dialog.show()
    }

    /**
     * 拍照
     */
    private fun takePhoto() {

        val fileName = StringBuilder()
        val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

        fileName.append(UUID.randomUUID()).append("_upload.png")
        val tempFile = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString())
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
            val uri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", tempFile)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        } else {
            val uri = Uri.fromFile(tempFile)
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        }
        mCurrentPhotoPath = tempFile.getAbsolutePath()
        context.startActivityForResult(intent, REQUEST_CODE_CAMERA)

    }

    /**
     * 选择相册照片
     */
    private fun chooseAlbumPic() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/*"
        context.startActivityForResult(intent,REQUEST_CODE_ALBUM)

    }

    internal var mHandler: Handler? = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            takePhoto()
        }
    }

}

